﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace TencentMapSdk
{
    /// <summary>
    /// 查询字符串建造者
    /// </summary>
    internal class GetRequestBuilder
    {
        /// <summary>
        /// 描述查询参数Key-Value键值对。其中 IsUrlEncode 表示 Value值是否需要Url编码
        /// </summary>
        SortedDictionary<string, (string ParameterValue, bool IsUrlEncode)> dic;
        string secretKey;
        string url;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static GetRequestBuilder Create(string secretKey, string url)
        {
            return new GetRequestBuilder()
            {
                dic = new SortedDictionary<string, (string ParameterValue, bool IsUrlEncode)>(),
                secretKey = secretKey,
                url = url
            };
        }

        /// <summary>
        /// 创建Get请求
        /// </summary>
        /// <returns></returns>
        public string BuildQueryString()
        {
            StringBuilder signBuilder = new StringBuilder();
            StringBuilder queryBuilder = new StringBuilder();
            foreach (var item in dic)
            {
                signBuilder.Append($"&{item.Key}={item.Value.ParameterValue}");

                string value = item.Value.IsUrlEncode ?
                    HttpUtility.UrlEncode(item.Value.ParameterValue)
                    : item.Value.ParameterValue;
                queryBuilder.Append($"&{item.Key}={value}");
            }
            if (dic.Count <= 0)
            {
                return null;
            }
            //签名字符串
            string signStr = url + "?" + signBuilder.ToString()[1..] + secretKey;
            //Get请求字符串
            string queryUrl = url + "?" + queryBuilder.ToString()[1..] + "&sig=" + Util.MD5(signStr);
            return queryUrl;
        }

        /// <summary>
        /// 设置Key-Value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public GetRequestBuilder WithKeyValue(string key, string value, bool isUrlEncode = false)
        {
            if (!string.IsNullOrWhiteSpace(value))
            {
                dic[key] = (value, isUrlEncode);
            }
            return this;
        }

        /// <summary>
        /// 设置Key-Value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public GetRequestBuilder WithKeyValue(string key, object value)
        {
            if (value!=null)
            {
               dic[key] = (value.ToString(), false);
            }
            return this;
        }
    }
}
